package com.hongtech.tiny.modules.app.utils;

import com.hongtech.tiny.modules.knowledge.entity.UserEntity;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * jwt工具类
 */
@Data
@Slf4j
@Component
@ConfigurationProperties(prefix = "app.jwt")
public class AppJwtUtils {

    private static final String CLAIM_KEY_MOBILE = "sub";

    private static final String CLAIM_KEY_CREATED = "created";

    /**
     * token私钥
     */
    private String appSecret;

    /**
     * 过期时间
     */
    private Long appExpiration;

    /**
     * 请求头值
     */
    private String appHeader;

    /**
     * 根据负责生成JWT的token
     */
    private String generateToken(Map<String, Object> claims) {
        return Jwts.builder()
                .setClaims(claims)
                .setExpiration(generateExpirationDate())
                .signWith(SignatureAlgorithm.HS512, appSecret)
                .compact();
    }

    /**
     * 从token中获取JWT中的负载
     */
    private Claims getClaimsFromToken(String token) {
        Claims claims = null;
        try {
            claims = Jwts.parser()
                    .setSigningKey(appSecret)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            log.info("JWT格式验证失败:{}", token);
        }
        return claims;
    }

    /**
     * 生成token的过期时间
     */
    private Date generateExpirationDate() {
        return new Date(System.currentTimeMillis() + appExpiration * 1000);
    }

    /**
     * 根据用户信息生成token
     */
    public String getAppToken(UserEntity user) {
        Map<String, Object> claims = new HashMap<>();
        claims.put(CLAIM_KEY_MOBILE, user.getMobile());
        claims.put(CLAIM_KEY_CREATED, new Date());
        return generateToken(claims);
    }

    /**
     * 从token中获取登录用户名
     */
    public String getMobileFromToken(String token) {
        String username = "";
        try {
            Claims claims = getClaimsFromToken(token);
            username = claims != null ? claims.getSubject() : "";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return username;
    }

    /**
     * 验证token是否还有效
     *
     * @param token 客户端传入的token
     * @param user  从数据库中查询出来的用户信息
     */
    public boolean validateToken(String token, UserEntity user) {
        String username = getMobileFromToken(token);
        return username.equals(user.getMobile()) && !isTokenExpired(token);
    }

    /**
     * 判断token是否已经失效
     */
    private boolean isTokenExpired(String token) {
        Date expiredDate = getExpiredDateFromToken(token);
        if (expiredDate != null) {
            return expiredDate.before(new Date());
        }
        return false;
    }

    /**
     * 从token中获取过期时间
     */
    private Date getExpiredDateFromToken(String token) {
        Claims claims = getClaimsFromToken(token);
        return claims != null ? claims.getExpiration() : null;
    }

}
